import json
from channels.generic.websocket import AsyncWebsocketConsumer, AsyncJsonWebsocketConsumer
from django.http import request

"""
给群组里的指定人发消息：
原理：每个人有一个自己的标识，每一个对象都有一个自己的 scope, receive, send, 把每个人的存起来，调用指定人的send去发送就行
"""

send_dict = {}

class ChatConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.uid = self.scope["query_string"].decode()
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = f"chat_{self.room_name}"
        # 加入组
        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        if not send_dict:
            send_dict[self.room_group_name] = {}
        send_dict[self.room_group_name][self.uid] = self.send_json
        print(send_dict)
        await self.accept()


    async def disconnect(self, code):
        del send_dict[self.room_group_name][self.uid]
        await self.channel_layer.group_discard(
            self.room_group_name, self.channel_name
        )

    """ AsyncJsonWebsocketConsumer 实现 """
    async def receive_json(self, text_data=None):
        print(text_data)
        # 发送消息到 room group
        # await self.channel_layer.group_send(
        #     self.room_group_name, {"type": "chat.message", "message": text_data['message']}
        # )
        print(send_dict)
        await send_dict[self.room_group_name]['uid=222']({"message":text_data['message'] })

    
    # 接收消息从 room group
    async def chat_message(self, event):
        print(event)
        # Send message to WebSocket
        await self.send_json({"message": event["message"]})
    
    """ AsyncWebsocketConsumer 实现 """
    # 接收消息从websocket
    # async def receive(self, text_data=None):
    #     text_data_json = json.loads(text_data)
    #     message = text_data_json["message"]
    #     # 发送消息到 room group
    #     await self.channel_layer.group_send(
    #         self.room_group_name, {"type": "chat.message", "message": message}
    #     )

    
    # # 接收消息从 room group
    # async def chat_message(self, event):
    #     message = event["message"]

    #     # Send message to WebSocket
    #     await self.send(text_data=json.dumps({"message": message}))